<?php

namespace ExAdmin\ui\component\detail;

use ExAdmin\ui\component\grid\descriptions\DescriptionsItem;
use ExAdmin\ui\support\Arr;
use ExAdmin\ui\traits\Display;

class Item extends DescriptionsItem
{
    use Display;

    protected $data = [];

    protected $field;

    protected $closure = [];
    protected $displayValue = null;
    protected $displayComponent = null;

    protected $default = '';
    public function __construct($field, $label, $data)
    {
        $this->data = $data;
        $this->field = $field;
        $this->attr('title',$label);
        $this->label($label);
        parent::__construct();
    }
    public function getField(){
        return $this->field;
    }
    /**
     * 设置缺失值
     * @param $value
     */
    public function default($value){
        $this->default = $value;
    }
    /**
     * 自定义显示
     * @param \Closure $closure
     * @return $this
     */
    public function display(\Closure $closure)
    {
        $this->closure[] = $closure;
        return $this;
    }

    public function jsonSerialize()
    {
        if(is_null($this->field)){
            $originValue =null;
        }else{
            $originValue = Arr::get($this->data, $this->field);
        }
        if (is_null($originValue)) {
            $value = $this->default;
        } else {
            $value = $originValue;
        }
        //自定义内容显示处理
        foreach ($this->closure as $key=>$display){
            if($key === 0){
                $this->displayValue = $originValue;
                $this->displayComponent = $originValue;
            }
            $display->bindTo($this);
            $value = call_user_func_array($display,[$originValue, $this->data]);
            $this->displayComponent = $value;
            if(!is_object($value)){
                $this->displayValue = $value;
            }
        }
        $this->content($value);
        return parent::jsonSerialize(); // TODO: Change the autogenerated stub
    }
}
